package org.mmw.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mmw.common.Result;
import org.mmw.entity.Book;
import org.mmw.service.BookService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/system/book")
@Api(tags = "图书接口")
public class BookController {

    @Resource
    BookService bookService;


    @GetMapping("/select")
    @ApiOperation(value = "查询图书")
    public Result select(@RequestParam(required = false) String key){
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(key)){
            wrapper.like(Book::getBookName,key);
        }
        List<Book> list = bookService.list(wrapper);
        return Result.build(list,"查询成功",200);
    }

    @GetMapping("/select/{id}")
    @ApiOperation(value = "根据id查询图书")
    public Result selectById(@PathVariable("id") Long id){

        Book book = bookService.getById(id);

        return Result.build(book,"查询成功",200);
    }


    @PostMapping("/add")
    @ApiOperation(value = "添加图书")
    public Result add(@RequestBody Book book){
        String isbn = book.getIsbn();
        if (StringUtils.isEmpty(isbn)){
            return Result.build(null,"ISBN编号为空",40010);
        }

        book.setCreateTime(new Date());
        book.setUpdateTime(new Date());
        bookService.save(book);
        return Result.build(null,"添加成功",200);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改图书")
    public Result update(@RequestBody Book book){

        book.setUpdateTime(new Date());

        bookService.updateById(book);

        return Result.build(null,"修改成功",200);

    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "删除图书")
    public Result delete(@PathVariable("id") Long id){

        bookService.removeById(id);

        return Result.build(null,"删除成功",200);

    }

}
